<template>
  <div class="role-manager-container">
    <div class="set-icon-header" style="padding: 24px 24px 0 24px">
      <el-form
        ref="form"
        label-position="left"
        :model="roleManagerSearch"
        label-width="100px"
      >
        <el-row :gutter="15">
          <el-col :span="7">
            <el-form-item label="角色名称：">
              <el-input
                v-model.trim="roleManagerSearch.name"
                show-word-limit
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div style="position: relative;top: 5px;">
              <el-button
                type="primary"
                @click="queryMethods"
              >
                查询
              </el-button>
              <el-button
                type="primary"
                @click="addNewRoleMethods"
              >
                新增
              </el-button>
              <el-button
                type="danger"
                @click="showMutiDelConfirm"
                icon="el-icon-delete"
              >
                批量删除
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="set-icon-header">
      <CommonTable
        ref="roleListRef"
        v-loading="isLoading"
        :is-selection="true"
        :is-show-index="false"
        :t-column-data="roleManagerCol"
        :remote-api="roleListService"
        :is-has-opera="true"
        row-key="roleId"
        :is-reserve-select="true"
        @changeRow="changeSelectionList"
      >
        <template
          slot="operate"
          slot-scope="scope"
        >
          <div
            v-if="scope.row.roleId !== 1"
            class="do-list"
          >
          <span
            @click="getRoleDetailById(scope.row)"
          >编辑</span>

            <span
              class="del-button"
              v-if="scope.row.name !== '超级管理员'"
              @click="delRoleConfirm(scope.row)"
            >删除</span>
          </div>
        </template>
      </CommonTable>
    </div>
<!--    <el-pagination-->
<!--      class="page-nation"-->
<!--      :current-page="roleManagerSearch.page"-->
<!--      :page-sizes="[10, 20, 30, 40]"-->
<!--      :page-size="roleManagerSearch.size"-->
<!--      layout="total, sizes, prev, pager, next, jumper"-->
<!--      :total="total"-->
<!--      @size-change="handleSizeChange"-->
<!--      @current-change="handleCurrentChange"-->
<!--    />-->

    <el-dialog
      :close-on-click-modal="false"
      :title="addRoleModel.roleId?'角色编辑': '角色新增'"
      :visible.sync="isShowAddRole"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="roleModelForm"
        :rules="roleRules"
        :model="addRoleModel"
        label-width="80px"
      >
        <el-form-item
          label="角色名称"
          prop="name"
        >
          <el-input
            v-model.trim="addRoleModel.name"
            show-word-limit
            maxlength="30"
          />
        </el-form-item>
<!--        <el-form-item-->
<!--          label="父级角色"-->
<!--          prop="name"-->
<!--        >-->
<!--          <el-select-->
<!--            v-model="addRoleModel.parentId"-->
<!--            class="add-person-input"-->
<!--            placeholder="请选择"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="item in roleList"-->
<!--              :key="item.id"-->
<!--              :label="item.name"-->
<!--              :value="item.id"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item
          label="角色权限"
          prop="rolePerms"
        >
          <el-tree
            ref="menuTree"
            :data="treeData"
            show-checkbox
            node-key="id"
            :default-expanded-keys="hasCheckedTree"
            :check-strictly="ischeckStrictly"
            :props="defaultProps"
            @check-change="changeRoleAuth"
          />
        </el-form-item>
<!--        prop="roleDesc"-->
        <el-form-item
          label="角色描述"
        >
          <el-input
            v-model.trim="addRoleModel.description"
            show-word-limit
            maxlength="30"
          />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="handleClose">取 消</el-button>
        <el-button
          type="primary"
          @click="addNewRole"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!--人员分配-->
    <el-dialog
      :close-on-click-modal="false"
      :title="'人员分配-' + clickRoleCache.name"
      :visible.sync="isShowGiveRoleAuth"
      width="70%"
      :before-close="handleClose"
    >
      <div class="give-role-auth-container">
        <div>
          <div class="give-title">
            可选列表
          </div>
          <el-input
            v-model="searchCanSelect"
            placeholder="请输入姓名或手机号码"
            suffix-icon="el-icon-search"
            @input="changeSearchCanSelect"
          />
          <el-table
            ref="multipleTable"
            border
            class="selection-table"
            :data="unallocatedDataList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleCanSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column
              prop="nickName"
              label="姓名"
              width="120"
            />
            <el-table-column
              prop="userName"
              label="用户名"
              width="120"
            />
            <el-table-column
              prop="phone"
              label="手机号"
              width="120"
            />
          </el-table>
        </div>
        <div>

          <div class="chanshuo-arrow-row">
            <div>
              <el-button @click="changeClassToSelected('selected')" type="primary">分配角色 ></el-button>
            </div>
            <!--            <img @click="changeClassToSelected('selected')" src="@/assets/chuansuo_right_keyong@2x.png" alt="">-->
            <div>
              <el-button @click="changeClassToSelected('unSelect')" type="primary">< 取消角色</el-button>
            </div>
            <!--            <img @click="changeClassToSelected('unSelect')" src="@/assets/chuansuo_left_keyong@2x.png" alt="">-->
          </div>
<!--          <div class="chanshuo-arrow-row">-->
<!--            <img @click="changeClassToSelected('selected')" src="@/assets/chuansuo_right_keyong@2x.png" alt="">-->

<!--            <img @click="changeClassToSelected('unSelect')" src="@/assets/chuansuo_left_keyong@2x.png" alt="">-->
<!--          </div>-->

<!--          <div-->
<!--            class="icon-big el-icon-right"-->
<!--            @click="changeClassToSelected('selected')"-->
<!--          />-->
<!--          <div-->
<!--            class="icon-big el-icon-back"-->
<!--            @click="changeClassToSelected('unSelect')"-->
<!--          />-->
        </div>
        <div>
          <div class="give-title">
            已选列表
          </div>
          <el-input
            v-model="searchHasCanSelect"
            placeholder="请输入姓名或手机号码"
            suffix-icon="el-icon-search"
            @input="changeSearchHasSelect"
          />
          <el-table
            ref="multipleTable"
            border
            class="selection-table"
            :data="allocatedDataList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleHasSelectedChange"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column
              prop="nickName"
              label="姓名"
              width="120"
            />
            <el-table-column
              prop="userName"
              label="用户名"
              width="120"
            />
            <el-table-column
              prop="phone"
              label="手机号"
              width="120"
            />
          </el-table>
        </div>

        <div class="float-ryfp-tips">
          注意：每个人员只能同时使用一种角色权限，分配新的角色权限将自动失去原来的角色权限
        </div>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="handleClose">取 消</el-button>
        <el-button
          type="primary"
          @click="confirmGiveRoleConfig"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!--删除提示-->
    <el-dialog
      title=""
      :visible.sync="warnningDialog"
      width="20%"
      :close-on-click-modal="false"
      :before-close="handleWarnClose"
      center
    >
      <div class="warn-container-box">
        <div class="flex-row">
          <div class="el-icon-warning-outline big-icon" />
          <div class="warn-words">
            删除提醒
          </div>
        </div>
        <div class="small-tips">
          此操作为不可逆，请谨慎处理!
        </div>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="handleWarnClose">取 消</el-button>
        <el-button
          type="primary"
          @click="confirmDelMethods"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CommonTable from '@/components/CommonTable/Table'
import { roleManagerCol } from './tableCol/roleManagerCol'
import * as service from './service'
export default {
  name: 'Role',
  data() {
    const validateTree = (rule, value, callback) => {
      const checkedTree = this.$refs.menuTree.getCheckedNodes()
      if (checkedTree.length === 0) {
        callback(new Error('请选择菜单'))
      } else {
        callback()
      }
    }
    return {
      roleList: [],
      allRoleList: [],
      roleListService: service.getRoleList,
      ischeckStrictly: false,
      searchCanSelect: '',
      searchHasCanSelect: '',
      isShowGiveRoleAuth: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      roleRules: {
        name: [
          { required: true, message: '请填写角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请填写角色描述', trigger: 'blur' }
        ],
        rolePerms: [
          { required: true, validator: validateTree, trigger: 'change' }
        ]
      },
      hasCheckedTree: [],
      roleManagerList: [],
      addRoleModel: {
        rolePerms: [],
        name: '',
        description: '',
        parentId: ''
      },
      roleManagerCol,
      roleManagerSearch: {
        pageNum: 1,
        pageSize: 20
      },
      total: 0,
      isShowAddRole: false,
      canSelectionList: [],
      hasSelectedList: [],
      isLoading: false,
      warnningDialog: false,
      clickRowCache: {},
      delRoleList: [],
      userInfo: {},
      unallocatedDataList: [],
      unallocatedDataListHistory: [],
      allocatedDataList: [],
      allocatedDataListHistory: [],
      clickRoleCache: {}
    }
  },
  component: {
    CommonTable
  },
  mounted() {
    this.userInfo = JSON.parse(window.localStorage.getItem('userInfo'))
    this.getMenuList()
    this.getRoleList()
    this.getTreeList()
    this.getAllList()
  },
  methods: {
    getAllList() {
      service.getRoleList({page: 1, pageSize: 200000000}).then((res) => {
        this.allRoleList = [...res.data.records]
      })
    },
    getTreeList() {
      service.getRoleTree({}).then((res) => {
        console.log('res.data ---', res)
      })
    },
    confirmGiveRoleConfig() {
      const allocatedData = []
      this.allocatedDataList.forEach((item) => {
        allocatedData.push(item.userId)
      })
      const params = {
        roleId: this.clickRoleCache.roleId,
        userIds: allocatedData.join(',')
      }
      // if(params.userIds === '') {
      //   this.$message.error('请从可选列表选择一个到已选中')
      //   // this.handleClose()
      //   return
      // }

      service.batchAuth(params).then(() => {
        this.$message.success('分配成功')
        this.handleClose()
      })
    },
    changeClassToSelected(type) {
      if (type === 'selected') {
        this.allocatedDataList = new Set([...this.canSelectionList, ...this.allocatedDataList])
        this.allocatedDataList = [...this.allocatedDataList].slice()
        this.allocatedDataListHistory = [...this.allocatedDataList].slice()
        this.allocatedDataList.splice(0, 0)
        this.unallocatedDataList.splice(0, 0)

        // 删除选中数据
        this.canSelectionList.forEach((item) => {
          const findIndex = this.unallocatedDataList.findIndex((result) => {
            return result.userId === item.userId
          })
          if (findIndex !== -1) {
            this.unallocatedDataList.splice(findIndex, 1)
          }
        })
      }

      if(type === 'unSelect') {
        this.unallocatedDataList = new Set([...this.hasSelectedList, ...this.unallocatedDataList])
        this.unallocatedDataList = [...this.unallocatedDataList].slice()
        this.unallocatedDataList.splice(0, 0)
        this.allocatedDataList.splice(0, 0)

        this.unallocatedDataListHistory = [...this.unallocatedDataList].slice()
        // 删除选中数据
        this.hasSelectedList.forEach((item) => {
          const findIndex = this.allocatedDataList.findIndex((result) => {
            return result.userId === item.userId
          })
          if (findIndex !== -1) {
            this.allocatedDataList.splice(findIndex, 1)
          }
        })
      }
    },
    changeSearchHasSelect(val) {
      console.log('val ---', val)
      if (val === '') {
        this.allocatedDataList = this.allocatedDataListHistory.slice()
      } else {
        const tmpArr = []
        this.allocatedDataList.forEach((item) => {
          if (item.userName.indexOf(val) !== -1) {
            tmpArr.push(item)
          }
        })
        if(tmpArr.length === 0) {
          this.allocatedDataList.forEach((item) => {
            if (item.phone.indexOf(val) !== -1) {
              tmpArr.push(item)
            }
          })
        }
        this.allocatedDataList = tmpArr.slice()
      }
    },
    changeSearchCanSelect(val) {
      if (val === '') {
        this.unallocatedDataList = this.unallocatedDataListHistory.slice()
      } else {
        const tmpArr = []
        this.unallocatedDataList.forEach((item) => {
          if (item.userName.indexOf(val) !== -1) {
            tmpArr.push(item)
          }
        })

        if(tmpArr.length === 0) {
          this.unallocatedDataList.forEach((item) => {
            if (item.phone.indexOf(val) !== -1) {
              tmpArr.push(item)
            }
          })
        }
        this.unallocatedDataList = tmpArr.slice()
      }
    },
    getUnAllocatedListMethods(roleId) {
      const params = {
        roleId: roleId
      }
      service.unallocatedList(params).then((res) => {
        res.data.rows = res.data.rows.filter((result) => {
          return result.userName !== 'admin'
        })
        this.unallocatedDataList = res.data.rows.slice()
        this.unallocatedDataListHistory = res.data.rows.slice()
      })
    },
    getAllocatedListMethods(roleId) {
      const params = {
        roleId: roleId
      }
      service.allocatedList(params).then((res) => {
        console.log('res.data ---', res)
        this.allocatedDataList = res.data.rows.slice()
        this.allocatedDataListHistory = res.data.rows.slice()
      })
    },
    changeRoleAuth() {
      this.$refs.roleModelForm.validate()
    },
    changeSelectionList(val) {
      this.delRoleList = val.slice()
    },
    confirmDelMethods() {
      const params = {
        roleIds: []
      }
      if (Object.keys(this.clickRowCache).length > 0) {
        params.roleIds = [{id: this.clickRowCache.roleId}]
      }

      if (this.delRoleList.length > 0) {
        const roleIdList = []
        this.delRoleList.forEach((item) => {
          roleIdList.push({
            id: item.roleId
          })
        })
        if (roleIdList.indexOf('1') !== -1) {
          this.$message.error('超级管理员不能删除啊')
          return
        }

        params.roleIds = roleIdList
      }

      service.delRoleById(params.roleIds).then(() => {
        this.$message.success('删除成功')
        this.roleManagerSearch.pageNum = 1
        this.handleWarnClose()
        this.getRoleList()
        // 清空选中
        this.$refs.roleListRef.clearSelectionMethods()
      }).catch((err) => {

      })
    },
    handleWarnClose() {
      this.clickRowCache = {}
      this.warnningDialog = false
      this.delRoleList = []
    },
    showMutiDelConfirm() {
      if (this.delRoleList.length === 0) {
        this.$message.error('请选择删除的角色')
        return
      }
      this.warnningDialog = true
    },
    delRoleConfirm(row) {
      this.clickRowCache = Object.assign({}, row)
      this.warnningDialog = true
    },
    queryMethods() {
      this.roleManagerSearch.page = 1
      this.getRoleList()
    },
    getRoleDetailById(row) {
      const params = {
        id: row.id
      }
      this.hasCheckedTree = []
      this.isLoading = true
      service.getRoleDetail(params).then((res) => {
        this.isLoading = false
        // 过滤roleList
        let findIndex = this.allRoleList.findIndex((result) => {
          return result.name === row.name
        })
        this.roleList = JSON.parse(JSON.stringify(this.allRoleList))
        if(findIndex !== -1) {
          this.roleList.splice(findIndex, 1)
        }
        this.hasCheckedTree = res.data.rolePerms.slice()
        this.ischeckStrictly = true
        this.$nextTick(() => {
          this.$refs.menuTree.setCheckedKeys(res.data.rolePerms) //给树节点赋值
          this.ischeckStrictly = false
        })
        this.addRoleModel.name = res.data.name
        this.addRoleModel.description = res.data.description
        this.addRoleModel.roleId = res.data.id
        this.addRoleModel.rolePerms = res.data.rolePerms.slice()
        this.addRoleModel.parentId = res.data.parentId
        if(this.addRoleModel.parentId == 0) {
          this.addRoleModel.parentId = ''
        }
        this.isShowAddRole = true
      })
    },
    addNewRole() {
      const checkedTree = this.$refs.menuTree.getCheckedNodes(false, true)
      const menuIds = []
      checkedTree.forEach((item) => {
        menuIds.push(item.id)
      })
      // this.addRoleModel.menuIds = menuIds.slice()
      this.$refs.roleModelForm.validate((valid) => {
        if (valid) {
          const params = Object.assign({}, this.addRoleModel)

          delete params.menuIds
          params.rolePerms = menuIds.slice()
          if (this.addRoleModel.roleId) {
            params.id = this.addRoleModel.roleId
            delete params.roleId
            this.isLoading = true
            service.editOldRole(params).then(() => {
              this.isLoading = false
              this.$message.success('编辑成功')
              this.getRoleList()
              this.handleClose()
            }).catch(() => {
              this.isLoading = false
            })
          } else {
            this.isLoading = true
            service.addNewRole(params).then(() => {
              this.isLoading = false
              this.$message.success('编辑成功')
              this.getRoleList()
              this.handleClose()
            }).catch(() => {
              this.isLoading = false
            })
          }
        }
      })
    },
    getMenuList() {
      service.getMenuList({}).then((res) => {
        res.data.forEach((item) => {
          if(item.label === '会议列表') {
            item.children = [{...item.children[0]}]
          }
        })
        this.treeData = res.data.slice()
      })
    },
    getRoleList() {
      this.isLoading = true
      const params = Object.assign({}, this.roleManagerSearch)
      this.$refs.roleListRef.queryData(params, () => {
        this.isLoading = false
      })
    },
    giveRoleAuth(row) {
      this.clickRoleCache = Object.assign({}, row)
      this.getAllocatedListMethods(row.roleId)
      this.getUnAllocatedListMethods(row.roleId)
      this.isShowGiveRoleAuth = true
    },
    handleHasSelectedChange(val) {
      this.hasSelectedList = val.slice()
    },
    handleCanSelectionChange(val) {
      this.canSelectionList = val.slice()
    },
    handleClose() {
      // 清空选中节点
      this.searchCanSelect = ''
      this.searchHasCanSelect = ''
      if (this.$refs.menuTree) {
        this.$refs.menuTree.setCheckedKeys([])
      }
      this.isShowAddRole = false
      this.isShowGiveRoleAuth = false
      this.addRoleModel = Object.assign({}, {
        name: '',
        description: ''
      })
      this.clickRoleCache = {}
    },
    addNewRoleMethods() {
      this.isShowAddRole = true
    },
    handleSizeChange(size) {
      this.roleManagerSearch.pageSize = size
      this.getRoleList()
    },
    handleCurrentChange(page) {
      this.roleManagerSearch.pageNum = page
      this.getRoleList()
    }
  }
}
</script>

<style scoped lang="scss">
    .give-title{
        margin-bottom: 15px;
    }
    .role-manager-container{
      padding: 15px;
  background-color: #fff;
    }
    .page-nation{
        margin-top: 15px;
        text-align: right;
    }
    .give-role-auth-container{
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }
    .selection-table{
        margin-top: 15px;
    }
    .icon-big{
        display: block;
        font-size: 36px;
        cursor: pointer;
        position: relative;
        top: 79px;
    }
    .big-icon{
        font-size: 42px;
    }
    .flex-row{
        display: flex;
        align-items: center;
        font-size: 18px;
        justify-content: center;
    }
    .warn-container-box{
        text-align: center;
    }
    .warn-words{
        margin-left: 30px;
    }
    .small-tips{
        margin-top: 15px;
    }
    .do-list {
      span {
        display: inline-block;
        margin-right: 20px;
        cursor: pointer;
        color: #409EFF;
        &.del-button{
          color: #F56C6C;
        }
      }
    }

    .chanshuo-arrow-row{
      position: relative;
      top: 120px;
      div{
        margin-top: 20px;
      }
      img{
        width: 48px;
        height: 48px;
        display: block;
        margin-top: 15px;
      }
    }
    .float-ryfp-tips{
      position: absolute;
      left: 20px;
      bottom: 20px;
      color: #F56C6C;
      font-size: 14px;
    }
</style>
